package com.scvtc.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scvtc.domain.ResResult;
import com.scvtc.domain.dto.common.SystemLoginUser;
import com.scvtc.domain.dto.common.SystemUserLoginDto;
import com.scvtc.domain.dto.system.menu.SystemMenuDto;
import com.scvtc.domain.dto.system.menu.SystemMenuUpdateDto;
import com.scvtc.domain.entity.system.SystemMenu;
import com.scvtc.domain.entity.system.SystemRole;
import com.scvtc.domain.vo.PageVo;
import com.scvtc.mapper.system.SystemMenuMapper;
import com.scvtc.mapper.system.SystemRoleMapper;
import com.scvtc.service.system.SystemMenuService;
import com.scvtc.service.system.SystemUserService;
import com.scvtc.utils.BeanCopyUtils;
import com.scvtc.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.scvtc.constants.RedisConstant.USER_LOGIN;

/**
 * 菜单管理(SystemMenu)表服务实现类
 *
 * @author yiFei
 * @since 2022-04-13 17:38:28
 */
@Service("systemMenuService")
public class SystemMenuServiceImpl extends ServiceImpl<SystemMenuMapper, SystemMenu> implements SystemMenuService {

    @Resource
    private SystemRoleMapper systemRoleMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SystemUserService systemUserService;

    /**
     * 根据用户id查询用户菜单ids
     *
     * @param id
     * @return
     */
    @Override
    public ResResult<List<Long>> getMenusByUserId(Long id) {
        // 根据 id 拿到菜单
        List<SystemRole> systemRoles = systemRoleMapper.getRolesByUserId(id);
        Set<Long> ids = systemRoles.stream()
                .map(SystemRole::getId)
                .collect(Collectors.toSet());
        // 根据 roleIds 拿到 菜单信息
        List<Long> menu_ids = getBaseMapper().getMenusByRoleIds(ids);
        return ResResult.noMsgSuccess(menu_ids);
    }


    /**
     * 获取所有菜单
     *
     * @return
     */
    @Override
    public ResResult<PageVo<List<SystemMenuUpdateDto>>> getAllMenus(@RequestParam(defaultValue = "1") Long current, @RequestParam(defaultValue = "10") Long size, String name) {
        // 查询全部
        Page<SystemMenu> page = page(new Page<>(current, size),
                new LambdaQueryWrapper<SystemMenu>()
                        .like(StringUtils.hasText(name), SystemMenu::getName, name)
        );
        // 封装展示
        List<SystemMenu> records = page.getRecords();
        List<SystemMenuUpdateDto> allMenu = BeanCopyUtils.copyBean(records, SystemMenuUpdateDto.class);
        long total = page.getTotal();
        return ResResult.noMsgSuccess(new PageVo<>(allMenu, total));
    }

    /**
     * 修改菜单
     *
     * @param systemMenuUpdateDto
     * @return
     */
    @Override
    public ResResult<?> updateMenus(SystemMenuUpdateDto systemMenuUpdateDto) {
        SystemMenu systemMenu = BeanCopyUtils.copyBean(systemMenuUpdateDto, SystemMenu.class);
        // 查看是否修改成功
        if (updateById(systemMenu)) {
            // 刷新 redis
            refreshAllLoginUser();
            return ResResult.success();
        }
        return ResResult.fail();
    }

    /**
     * 查询菜单（拥有子权限）
     *
     * @return
     */
    @Override
    public ResResult<List<SystemMenuDto>> getChildrenList() {
        List<SystemMenu> allMenus = getBaseMapper().getAllMenus(0L);
        List<SystemMenuDto> allMenuDtoList = recursionMenus(allMenus);
        return ResResult.noMsgSuccess(allMenuDtoList);
    }

    /**
     * 获取所有菜单
     *
     * @param menus
     * @return
     */
    private List<SystemMenuDto> recursionMenus(List<SystemMenu> menus) {
        List<SystemMenuDto> nav = new ArrayList<>();
        int count = 0;
        for (SystemMenu menu : menus) {
            nav.add(beanConvert(menu));
            if (menu.getChildren() != null && menu.getChildren().size() > 0) {
                nav.get(count).setChildren(recursionMenus(menu.getChildren()));
            }
            count++;
        }
        return nav;
    }

    /**
     * Bean 转换
     */
    private SystemMenuDto beanConvert(SystemMenu source) {
        SystemMenuDto systemMenuDto = BeanCopyUtils.copyBean(source, SystemMenuDto.class);
        systemMenuDto.setPermissionName(source.getPermission());
        return systemMenuDto;
    }

    /**
     * 异步刷新菜单任务
     */
    @Async("taskExecutor")
    public void refreshAllLoginUser() {
        Collection<String> keys = redisUtil.keys(USER_LOGIN.concat("*"));
        for (String key : keys) {
            SystemLoginUser systemLoginUser = redisUtil.getCacheObject(key);
            String username = systemLoginUser.getUsername();
            // TODO 使用加密算法解密 JasyptEncryptorUtil
            String password = systemLoginUser.getPassword();
            // 自动让用户重新登录
            systemUserService.login(new SystemUserLoginDto(username, password));
        }
    }
}

